﻿using System;
using System.Drawing;
using System.Text.RegularExpressions;
using Sunny.UI;

namespace DevelopTool.Common
{
    /// <summary>
    /// 颜色帮助类
    /// </summary>
    public static class ColorHelper
    {
        /// <summary>
        /// 获取随机颜色
        /// </summary>
        /// <param name="isDark"></param>
        /// <returns></returns>
        public static Color GetRandomColor(bool isDark = true)
        {
            if (isDark)
            {
                return GetColor();
            }
            else
            {
                return Color.FromArgb(RandomEx.Next(255), RandomEx.Next(255), RandomEx.Next(255));
            }
        }

        private static System.Drawing.Color GetColor()
        {
            int int_Red = RandomEx.Next(255);
            int int_Green = RandomEx.Next(255);
            int int_Blue = RandomEx.Next(255);

            int_Blue = (int_Red + int_Green > 380) ? int_Red + int_Green - 380 : int_Blue;
            int_Blue = (int_Blue > 255) ? 255 : int_Blue;

            return GetDarkerColor(System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue));
        }

        //获取加深颜色
        private static Color GetDarkerColor(Color color)
        {
            const int max = 255;
            int increase = new Random(Guid.NewGuid().GetHashCode()).Next(30, 255); //还可以根据需要调整此处的值

            int r = Math.Abs(Math.Min(color.R - increase, max));
            int g = Math.Abs(Math.Min(color.G - increase, max));
            int b = Math.Abs(Math.Min(color.B - increase, max));


            return Color.FromArgb(r, g, b);
        }

        /// <summary>
        /// 将字符串转换为Color
        /// 带#号的16进制颜色
        /// </summary>
        /// <param name="color">带#号的16进制颜色</param>
        /// <returns></returns>
        public static Color ToColor(string color)
        {

            int red, green, blue = 0;
            char[] rgb;
            color = color.TrimStart('#');
            color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
            switch (color.Length)
            {
                case 3:
                    rgb = color.ToCharArray();
                    red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
                    green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
                    blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
                    return Color.FromArgb(red, green, blue);
                case 6:
                    rgb = color.ToCharArray();
                    red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
                    green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
                    blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
                    return Color.FromArgb(red, green, blue);
                default:
                    return Color.FromName(color);

            }
        }

    }
}
